from PySide2.QtWidgets import QListWidget, QListWidgetItem
from PySide2.QtCore import QSize, Qt, Signal

from custom.VideoItem import VideoItem
from model import Video

class VideoListWidget(QListWidget):

    clickedImage = Signal(int, Video)
    updateUploador_signal = Signal()

    def __init__(self):
        super(VideoListWidget, self).__init__()
        self.list = []

    def clearData(self):
        for i in range(self.count()):
            item = self.item(i)
            widget = self.itemWidget(item)
            widget.clearData()
        
    def reloadData(self, list):
        self.clearData()
        self.list = list
        for i in range(len(list)):
            item = self.item(i)
            if item == None:
                self.setItem(list[i])
            else:
                widget = self.itemWidget(item)
                widget.reloadData(list[i])

    def setItem(self, video):
        item_widget = QListWidgetItem()
        item_widget.setFlags(Qt.ItemIsSelectable)
        item_widget.setSizeHint(QSize(200, 120))
        self.addItem(item_widget)

        videoWidget = VideoItem(video)
        videoWidget.clickedImage.connect(self.onClickImage)
        videoWidget.updateUploador_signal.connect(self.updateUploador_signal)
        self.setItemWidget(item_widget, videoWidget)

    def add_item(self, video):
        self.list.append(video)
        item_widget = QListWidgetItem()
        item_widget.setFlags(Qt.ItemIsSelectable)
        item_widget.setSizeHint(QSize(200, 120))
        self.addItem(item_widget)

        videoWidget = VideoItem(video)
        videoWidget.clickedImage.connect(self.onClickImage)
        videoWidget.updateUploador_signal.connect(self.updateUploador_signal)
        self.setItemWidget(item_widget, videoWidget)

    def remove_item(self, index):
        for i in range(self.count()):
            if index == i:
                item = self.takeItem(i)
               	self.removeItemWidget(item)
                break
        del self.list[index]

    def onClickImage(self, video):
        index = -1
        for i in range(len(self.list)):
            item = self.item(i)
            if item != None:
                widget = self.itemWidget(item)
                if widget.video.id == video.id:
                    index = i
                    break
        self.clickedImage.emit(index, video)
